#!/bin/bash
set -e

cd /app

# Cleanup any leftover pid file
if [ -f /app/tmp/pids/server.pid ]; then
  rm /app/tmp/pids/server.pid
fi

source /scripts/setup_env

# Fixup the Procfile and prepare the PORT
if [ -n "${DO_NOT_RUN_JOBS}" ]; then
  sed -i -e 's/^jobs:/#jobs:/' /app/Procfile
fi

IP="${IP:-0.0.0.0}"
sed -i -e "s/\${IP-0.0.0.0}/$IP/" -e "s/\${PORT-3000}/$PORT/" /app/Procfile

# initialize supervisord config
cat > /etc/supervisor/supervisord.conf <<EOF
[unix_http_server]
file=/dev/shm/supervisor.sock   ; (the path to the socket file)
chmod=0700                       ; sockef file mode (default 0700)

[supervisord]
nodaemon = true
stdout_logfile = AUTO
logfile=/var/log/supervisor/supervisord.log ; (main log file;default $CWD/supervisord.log)
pidfile=/app/tmp/pids/supervisord.pid ; (supervisord pidfile;default supervisord.pid)
childlogdir=/var/log/supervisor            ; ('AUTO' child log dir, default $TEMP)

; the below section must remain in the config file for RPC
; (supervisorctl/web interface) to work, additional interfaces may be
; added by defining them in separate rpcinterface: sections
[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface

[supervisorctl]
serverurl=unix:///dev/shm/supervisor.sock ; use a unix:// URL  for a unix socket

[eventlistener:stdout]
command = supervisor_stdout
buffer_size = 100
events = PROCESS_LOG
result_handler = supervisor_stdout:event_handler

; The [include] section can just contain the "files" setting.  This
; setting can list multiple files (separated by whitespace or
; newlines).  It can also contain wildcards.  The filenames are
; interpreted as relative to this file.  Included files *cannot*
; include files themselves.

[include]
files = /etc/supervisor/conf.d/*.conf
EOF

# prepare the supervisord bootstrap service script

cat <<BOOTSTRAP > /tmp/bootstrap.sh
#!/bin/bash -e
source /app/.env

echo DATABASE_HOST=\${DATABASE_HOST}

# start mysql server if \${DATABASE_HOST} is the .env.example default
if [ "\${START_MYSQL}" = "true" ]; then
  echo "DATABASE_SOCKET=/app/tmp/sockets/mysqld.sock" >> .env
  if [ "\${DATABASE_ADAPTER}" = "postgresql" ]; then
    echo "DATABASE_ADAPTER 'postgresql' is not supported internally. Please provide DATABASE_HOST."
    exit 1
  fi

  # configure supervisord to start mysql (manual)
  cat > /etc/supervisor/conf.d/mysqld.conf <<EOF
[program:mysqld]
priority=20
directory=/tmp
command=/usr/bin/mysqld_safe
autostart=false
autorestart=true
stdout_events_enabled=true
stderr_events_enabled=true
EOF
  supervisorctl reread
  supervisorctl add mysqld

  # initialize MySQL data directory
  if [ ! -d /var/lib/mysql/mysql ]; then
    mysql_install_db --user=\$(whoami) --datadir=/tmp/mysql
    mv -f /tmp/mysql/* /var/lib/mysql/
  fi

  echo "Starting mysql server..."
  supervisorctl start mysqld >/dev/null

  # wait for mysql server to start (max 120 seconds)
  timeout=120
  while ! mysqladmin -u root status >/dev/null 2>&1 && ! mysqladmin -u root --password=\${DATABASE_PASSWORD} status >/dev/null 2>&1
  do
    (( timeout = timeout - 1 ))
    if [ \$timeout -eq 0 ]; then
      echo "Failed to start mysql server"
      exit 1
    fi
    echo -n .
    sleep 1
  done

  if ! echo "USE \${DATABASE_NAME}" | mysql -u\${DATABASE_USERNAME:-root} \${DATABASE_PASSWORD:+-p\$DATABASE_PASSWORD} >/dev/null 2>&1; then
    echo "SET PASSWORD FOR 'root'@'localhost' = PASSWORD('\${DATABASE_PASSWORD:\$DATABASE_PASSWORD}');" | mysql -u root
  fi
fi
supervisorctl start foreman >/dev/null
BOOTSTRAP

chmod 755 /tmp/bootstrap.sh

cat > /etc/supervisor/conf.d/bootstrap.conf <<EOF
[program:bootstrap]
command=/tmp/bootstrap.sh
priority=10
directory=/app
process_name=%(program_name)s
autostart=true
autorestart=false
stdout_events_enabled=true
stderr_events_enabled=true
stopsignal=TERM
exitcodes=0
startsecs=0
stopwaitsecs=1
EOF

cat <<FOREMAN > /tmp/foreman.sh
#!/bin/bash -e
source /app/.env

# The database may need to start up for a bit first
if [ -n "\${INTENTIONALLY_SLEEP}" ]; then
  echo "Intentionally sleeping \${INTENTIONALLY_SLEEP}"
  sleep \${INTENTIONALLY_SLEEP}
fi

if [ -n "\${DATABASE_INITIAL_CONNECT_MAX_RETRIES}" ]; then
  max=\${DATABASE_INITIAL_CONNECT_MAX_RETRIES}
  count=0
  while ! rake database_test:ping > /dev/null 2>&1 && [[ \$count -le \$max ]] ; do
    count=\$[\$count+1]
    echo "Retry \$count of \$max attempting to connect to \$DATABASE_HOST. Sleeping \${DATABASE_INITIAL_CONNECT_SLEEP:5}"
    sleep \${DATABASE_INITIAL_CONNECT_SLEEP:5}
  done
fi

# We may need to try and create a database
if [ -z "\${DO_NOT_CREATE_DATABASE}" ]; then
  bundle exec rake db:create
fi

# Assuming we have a created database, run the migrations and seed it idempotently.
if [ -z "\${DO_NOT_MIGRATE}" ]; then
 bundle exec rake db:migrate
fi

if [ -z "\${DO_NOT_SEED}" ]; then
  bash -xc 'bundle exec rake db:seed &'
fi

# Start huginn
exec bundle exec foreman start
FOREMAN

chmod 755 /tmp/foreman.sh

cat > /etc/supervisor/conf.d/foreman.conf <<EOF
[program:foreman]
command=/tmp/foreman.sh
priority=10
directory=/app
process_name=%(program_name)s
autostart=false
autorestart=false
stdout_events_enabled=true
stderr_events_enabled=true
stopsignal=TERM
startsecs=0
stopwaitsecs=1
EOF

# start supervisord
exec /usr/bin/supervisord -c /etc/supervisor/supervisord.conf
